#! /bin/bash -

# set envrionment variables fisrtly
# GROUP=fibjs

usage()
{
	echo ""
	echo "Usage: `basename $0` [Command]"
	echo "Command:"
	echo "  image: "
	echo "      get build-env-alpine by docker."
	echo "  fibjs: "
	echo "      build fibjs."
	echo "  -h, --help:"
	echo "      Print this message and exit."
	echo ""
	exit 0
}

if [ "$FIBJS_DIR" = "" ]; then
    FIBJS_DIR=../../
fi
if [ "$GROUP" = "" ]; then
    GROUP=fibjs
fi
if [ "$IMG_NAME" = "" ]; then
    IMG_NAME=$GROUP/build-env-alpine
fi

image()
{
    docker build --rm -t $IMG_NAME .
}

fibjs()
{
    if [ "$DEBUG" != "" ]; then
        MODE=debug
        CI=""
    else
        MODE=release
        CI="ci"
    fi

    HOST_OS=`uname`
    CPU_CORE=2
    case ${HOST_OS} in
        Darwin)
            CPU_CORE=$(sysctl hw.ncpu | awk '{print $2}')
            ;;
        Linux)
            CPU_CORE=$(cat /proc/cpuinfo | grep processor | wc -l)
            ;;
        Windows)
            CPU_CORE=$(echo $NUMBER_OF_PROCESSORS)
            ;;
    esac

    BUILD_JOBS=$(( $CPU_CORE * 4 ))

    echo "------ env :start -------"
    echo HOST_OS: $HOST_OS
    echo CPU_CORE: $CPU_CORE
    echo BUILD_JOBS: $BUILD_JOBS
    echo "------ env :end   -------"

    echo "start compiling fibjs..."
    # -m 16g \
    # --memory-swap 32g \
    docker run -it \
        -e BUILD_JOBS=$BUILD_JOBS \
        -v ${FIBJS_DIR}:/home/ci $IMG_NAME:latest \
        /bin/sh -c "cd /home/ci; sh build $MODE $CI"
    echo "finish compiling fibjs!"
}

for i in "$@"
do
	case $i in
		image) image
			;;
		fibjs) fibjs
			;;
  		--help|-h) usage
			;;
        *) usage
            ;; 
	esac
done